package com.zhi.rabbitmq;

import com.zhi.domain.MiaoshaOrder;
import com.zhi.domain.MiaoshaUser;
import com.zhi.redis.RedisService;
import com.zhi.service.GoodsService;
import com.zhi.service.MiaoshaService;
import com.zhi.service.OrderService;
import com.zhi.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author WenZhi Luo
 * @version 1.0
 * @date 2020/3/14 14:21
 */
@Service
public class MQReceiver {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    RedisService redisService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;
    @RabbitListener(queues=MQConfig.MIAOSHA_QUEUE)
    public void receive(String message){
        log.info("receive MSG" + message);
        //接收到秒杀消息
        MiaoshaMessage mm  = RedisService.stringToBean(message, MiaoshaMessage.class);
        MiaoshaUser user = mm.getUser();
        long goodsId = mm.getGoodsId();

        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        //库存<=0直接丢掉就好了，因为经过层层拦截，实际上进到消息队列中来的已经很少了额...
        if(stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if(order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单，这三步应该是个原子操作
        miaoshaService.miaosha(user, goods);
    }
}